<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="98px">
      <el-form-item label="账单创建时间">
        <el-date-picker
          v-model="daterangeBillCreateTime"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="账单是否结算" prop="billIsPaid">
        <el-select v-model="queryParams.billIsPaid" placeholder="请选择账单是否结算" clearable size="small">
          <el-option
            v-for="dict in dict.type.sys_number_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bussiness:bill:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="billList" @selection-change="handleSelectionChange">
      <el-table-column label="账单人" align="center" prop="billUserName" />
      <el-table-column label="账单创建时间" align="center" prop="billCreateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.billCreateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账单状态" align="center" prop="billStatus" />
      <el-table-column label="账单是否结算" align="center" prop="billIsPaid">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_number_yes_no" :value="scope.row.billIsPaid"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleDetails(scope.row)"
            v-hasPermi="['bussiness:bill:details']"
          >查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改账单信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-card class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>未结算消费</span>
        </div>
        <el-table
          :data="tableData"
          show-summary
          style="width: 100%;">
          <el-table-column
            prop="type"
            align="center"
            label="消费类型">
          </el-table-column>
          <el-table-column
            prop="content"
            align="center"
            label="消费内容">
          </el-table-column>
          <el-table-column
            prop="time"
            align="center"
            label="消费时间">
          </el-table-column>
          <el-table-column
            prop="quantity"
            align="center"
            label="消费数量">
          </el-table-column>
          <el-table-column
            prop="isPaid"
            align="center"
            label="是否已结算">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_number_yes_no" :value="scope.row.isPaid"/>
            </template>
          </el-table-column>
          <el-table-column
            prop="amount"
            align="center"
            label="金额（元）">
          </el-table-column>
        </el-table>
      </el-card>
      <hr />
      <el-card class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>已结算消费</span>
        </div>
        <el-table
          :data="tableData2"
          style="width: 100%;">
          <el-table-column
            prop="type"
            align="center"
            label="消费类型">
          </el-table-column>
          <el-table-column
            prop="content"
            align="center"
            label="消费内容">
          </el-table-column>
          <el-table-column
            prop="time"
            align="center"
            label="消费时间">
          </el-table-column>
          <el-table-column
            prop="quantity"
            align="center"
            label="消费数量">
          </el-table-column>
          <el-table-column
            prop="isPaid"
            align="center"
            label="是否已结算">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_number_yes_no" :value="scope.row.isPaid"/>
            </template>
          </el-table-column>
          <el-table-column
            prop="amount"
            align="center"
            label="金额（元）">
          </el-table-column>
        </el-table>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSettle">结 算</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBill, delBill, getBillDetails, settleBill } from "@/api/bussiness/bill";

export default {
  name: "Bill",
  dicts: ['sys_number_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 账单信息表格数据
      billList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 账单是否结算时间范围
      daterangeBillCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        billCreateTime: null,
        billStatus: null,
        billIsPaid: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 账单列表数据
      tableData: [],
      tableData2: [],
      // 当前点击的账单
      currentBillId: ''
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询账单信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeBillCreateTime && '' != this.daterangeBillCreateTime) {
        this.queryParams.params["beginBillCreateTime"] = this.daterangeBillCreateTime[0];
        this.queryParams.params["endBillCreateTime"] = this.daterangeBillCreateTime[1];
      }
      listBill(this.queryParams).then(response => {
        this.billList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        billId: null,
        billUserName: null,
        billCreateTime: null,
        billStatus: null,
        billIsPaid: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeBillCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.billId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 查看账单详情按钮操作 */
    handleDetails(row) {
      if(!row.billId){
        return this.$modal.msgError("请选择一条账单");
      }
      this.reset();
      // 查询账单详情
      getBillDetails(row.billId).then(res=>{
        this.tableData = res.data.notPaidDetails
        this.tableData2 = res.data.paidDetails
        this.open = true;
        this.title = "查看账单详情";
        this.currentBillId = row.billId
      })
    },
    /** 结算按钮 */
    submitSettle() {
      let billId = this.currentBillId
      if(!billId){
        this.$modal.msgError("请选择一条账单信息！")
      }
      settleBill(billId).then(res => {
        this.$modal.msgSuccess("结算成功，若有押金将自动返回账户内！");
        this.getList();
        this.open = false
      })
      
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const billIds = row.billId || this.ids;
      this.$modal.confirm('是否确认删除账单信息编号为"' + billIds + '"的数据项？').then(function() {
        return delBill(billIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bussiness/bill/export', {
        ...this.queryParams
      }, `bill_${new Date().getTime()}.xlsx`)
    },
    /** 表格计算求和 */
    getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总价';
            return;
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] += ' 元';
          } else {
            sums[index] = 'N/A';
          }
        });

        return sums;
      }
  }
};
</script>

<style>
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 100%;
  }
</style>